#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QFileDialog>
#include <QDebug>
#include <iostream>
#include <QMatrix4x4>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent), ui(new Ui::MainWindow)
{
    ui->setupUi(this);
}

MainWindow::~MainWindow()
{
    delete ui;
}

QImage MainWindow::AdjustImageSize(QImage qimage, QLabel *qLabel) //调整图片大小与label相适应
{
    /*
     * 目前缩放用的Qimage类，需要改成自己的类
     */
    QImage image;
    QSize imageSize = qimage.size();
    QSize labelSize = qLabel->size();

    double dWidthRatio = 1.0 * imageSize.width() / labelSize.width();
    double dHeightRatio = 1.0 * imageSize.height() / labelSize.height();
    if (dWidthRatio > dHeightRatio)
    {
        image = qimage.scaledToWidth(labelSize.width());
    }
    else
    {
        image = qimage.scaledToHeight(labelSize.height());
    }
    return image;
}

void MainWindow::on_action_open_triggered()
{
    QString curDir = QDir::currentPath();
    QString filename = QFileDialog::getOpenFileName(this, "select Image", curDir,
                                                    "Images (*.bmp)");
    file_path = filename;
    if (filename.isEmpty())
    {
        return;
    }

    QImage img(filename);
    QImage image = AdjustImageSize(img, ui->label_show);

    std::cout << filename.toStdString() << std::endl;
    srcImage.ReadBMP(filename.toStdString().c_str());

    ui->label_show->setPixmap(QPixmap::fromImage(image));
    ui->label_show->setAlignment((Qt::AlignCenter));

    Is_show = false;
}

void MainWindow::on_action_save_triggered()
{
    QString curDir = QDir::currentPath();
    QString filename = QFileDialog::getSaveFileName(this, "save Image", curDir,
                                                    "Images (*.bmp)");
    if (filename.isEmpty() || srcImage.data == NULL)
    {
        return;
    }
    std::string save_path = filename.toStdString();
    srcImage.WriteBMP(save_path.c_str());
}

void MainWindow::on_action_Qimage_triggered()
{
    if (Is_show)
        return;

    if (srcImage.data == NULL)
        return;

    srcImage.Flip(1);
    QImage img(srcImage.data, srcImage.width/3, srcImage.height, QImage::Format_BGR888);
    QImage m_img = AdjustImageSize(img, ui->label_show);

    ui->label_show->setPixmap(QPixmap::fromImage(m_img));
    ui->label_show->setAlignment((Qt::AlignCenter));

    Is_show = true;
}

